/*
 * @Author: szx
 * @Date: 2022-02-20 12:53:07
 * @LastEditTime: 2022-02-20 13:49:07
 * @Description:
 * @FilePath: \leetcode\100-199\143\143.js
 */

function ListNode(val, next) {
    this.val = val === undefined ? 0 : val;
    this.next = next === undefined ? null : next;
}

/**
 * @param {ListNode} head
 * @return {void} Do not return anything, modify head in-place instead.
 */
var reorderList = function (head) {
    let mid = middleNode(head);
    let last = reverseList(mid.next);
    mid.next = null;
    return mergeList(head, last);
};

const middleNode = function (head) {
    let slow = head;
    let fast = head;
    while (fast && fast.next) {
        slow = slow.next;
        fast = fast.next.next;
    }
    return slow;
};

const reverseList = function (head) {
    let prev = null;
    let cur = head;
    while (cur != null) {
        const next = cur.next;
        cur.next = prev;
        prev = cur;
        cur = next;
    }
    return prev;
};
const mergeList = function (head1, head2) {
    const head = head1;
    while (head2) {
        const next2 = head2.next;
        head2.next = head1.next;
        head1.next = head2;
        head1 = head2.next;
        head2 = next2;
    }
    return head;
};
